package com.xwj.nio.tcp;

import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * nio通道channel之SocketChannel
 * TCP协议
 * @author xwj
 * @date 2020/6/10
 */
public class NioSendClient {
    public static void main(String[] args) throws Exception {
        String sourceFileName = "C:\\Users\\Administrator\\Desktop\\elasticsearch.yml";
        File sourceFile = new File(sourceFileName);
        FileChannel sourceFileChannel= new FileInputStream(sourceFile).getChannel();
        SocketChannel sc = SocketChannel.open();
        sc.socket().connect(new InetSocketAddress("127.0.0.1", 8888));
        sc.configureBlocking(false);
        while(!sc.finishConnect()) {
        }
        System.out.println("client连接服务器成功，开始发送文件");
        // 发送文件名称
        ByteBuffer fileNameBuf = Charset.forName("UTF-8").encode(sourceFile.getName());
        sc.write(fileNameBuf);
        // 发送文件长度
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.putLong(sourceFileName.length());
        buf.flip();
        sc.write(buf);
        buf.clear();
        // 发送文件内容
        int len = 0;
        while((len = sourceFileChannel.read(buf)) != -1) {
            // 变成读模式
            buf.flip();
            sc.write(buf);
            // 清空，变成写入模式
            buf.clear();
        }
        if(len == -1) {
            sourceFileChannel.close();
            sc.shutdownOutput();
        }
    }
}
